package cn.touna.jss.modules.custom.cheyiping;

import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.Car300Properties;
import cn.touna.jss.common.util.Common;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.custom.carmodel.entity.Car300BrandEntity;
import cn.touna.jss.modules.custom.carmodel.entity.Car300ModelEntity;
import cn.touna.jss.modules.custom.carmodel.entity.Car300SeriesEntity;
import cn.touna.jss.modules.custom.carmodel.mapper.*;
import cn.touna.jss.modules.custom.cheyiping.dto.CheyipingRequest;
import cn.touna.jss.modules.custom.cheyiping.dto.MaintenanceRecordRequest;
import cn.touna.jss.modules.custom.cheyiping.dto.PageRequest;
import cn.touna.jss.modules.custom.cheyiping.mapper.CityEntityMapper;
import cn.touna.jss.modules.third.car300.Car300Service;
import cn.touna.jss.modules.third.car300.entity.Car300Entity;
import cn.touna.jss.modules.third.car300.entity.Car300PriceRequestEntity;
import cn.touna.jss.modules.third.caridentify.CarIdentifyService;
import cn.touna.jss.modules.third.chaboshi.ChaboshiService;
import cn.touna.jss.modules.third.jzg.JingZhenGuService;
import cn.touna.jss.modules.third.tcredit.TcreditService;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.utils.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by Steve.Tao on 2017/8/23.
 */
@Service
public class CheyipingService {

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    private Car300Service car300Client;

    @Autowired
    private JingZhenGuService jingZhenGuClient;

    @Autowired
    private Car300BrandEntityMapper car300BrandEntityMapper;

    @Autowired
    private Car300SeriesEntityMapper car300SeriesEntityMapper;

    @Autowired
    private Car300ModelEntityMapper car300ModelEntityMapper;

    @Autowired
    private ModelMapEntityMapper modelMapEntityMapper;

    @Autowired
    private ModelUnmapedEntityMapper modelUnmapedEntityMapper;

    @Autowired
    private CityEntityMapper cityEntityMapper;

    private List<String> colors = Arrays.asList("米色", "棕色", "金色", "紫色", "巧克力色", "黑色", "蓝色", "灰色", "绿色", "红色", "橙色", "白色", "香槟色", "银色", "黄色");

    @Autowired
    Car300Properties car300Properties;


    /**
     * 评分矩阵： 三个方面，内饰，漆面，工况；四个层次：优,良,中,差
     */
    private double[][] ratio = {{1, 1, 1}, {0.986, 0.98, 0.97}, {0.975, 0.965, 0.945}, {0.96, 0.93, 0.9}};

    @Resource(name="executorService")
    private ExecutorService threadPool;

    @ApiMapping(value="cheyiping.getCarModel",desc="车易评.获取车型")
    public Response getCarModel(JSONObject requestEntity) {
        JSONObject params = requestEntity ;//requestEntity.getParams();
        String typeId =  params.getString("typeId");
        try {
            ValidUtil.notEmpty(typeId, "typeId不能为空");
            ValidUtil.notNumber(typeId, "typeId必须为数字");
        } catch (Exception e) {
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_PARAM_CHECK_FAILED, e.getMessage());
        }
        switch (typeId) {
            case "1":
                Car300Entity car300Entity = JSONUtil.jsonToObject(params, Car300Entity.class);
                return getCarModelByVin(car300Entity);
            case "2":
                PageRequest pageRequest = JSONUtil.jsonToObject(params, PageRequest.class);
                return getCarBrandList(pageRequest);
            case "3":
                CheyipingRequest.GetCarSeriesListRequest seriesListRequest = JSONUtil.jsonToObject(params, CheyipingRequest.GetCarSeriesListRequest.class);
                return getCarSeriesList(seriesListRequest);
            case "4":
                CheyipingRequest.GetCarModelListRequest carModelListRequest = JSONUtil.jsonToObject(params, CheyipingRequest.GetCarModelListRequest.class);
                return getCarModelList(carModelListRequest);
        }
        return ResponseFactory.fail(SystemErrorCodeEnum.CRS_PARAM_CHECK_FAILED, "typeId无效");
    }

    @ApiMapping(value="cheyiping.getCarModelById",desc="车易评.通过modelId获取车型")
    public Response getCarModelById(@RequestParam("modelId") int modelId){
        if(modelId < 1){
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED,"modelId数值异常");
        }
        Car300ModelEntity entity = car300ModelEntityMapper.selectByModelId(modelId);
        if(entity == null){
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_NO_DATA_FOUND,"无数据");
        }
        return ResponseFactory.success(entity);
    }

    /**
     * 根据vin获取车型号
     * @param request vin
     * @return
     */
    @ApiMapping(value="cheyiping.getCarModelByVin",desc="车易评.根据vin获取车型号")
    public Response getCarModelByVin(Car300Entity request) {
        Response response = null;
        try {
            String vin = request.getVin();
            ValidUtil.notEmpty(vin, "vin不能为空");
            request.setVin(vin.toUpperCase());
            response = car300Client.getCarModelByVin(request);
            if (!response.checkIfSuccess())
                return response;
        } catch (Exception e) {
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_PARAM_CHECK_FAILED, e.getMessage());
        }

        if (response != null && response.checkIfSuccess() && !StringUtils.isEmpty(response.getData())) {
            String str = (String) response.getData();
            JSONObject data = JSON.parseObject(str);
            if (data.getInteger("status") == 1) {
                JSONArray modelInfo = data.getJSONArray("modelInfo");
                JSONArray modelArray = new JSONArray();
//                Set<Integer> modelIdSet = new HashSet<>();
                for (int i = 0; i < modelInfo.size(); i++) {
                    JSONObject obj = modelInfo.getJSONObject(i);
                    JSONObject model = new JSONObject();
                    String modelId = obj.getString("model_id");
//                    modelIdSet.add(Integer.valueOf(modelId));
                    model.put("modelName", obj.getString("model_name"));
                    model.put("gearType", obj.getString("model_gear"));
                    model.put("liter", obj.getString("model_liter"));
                    model.put("modelId",modelId);
                    try{
                        Car300ModelEntity entity = car300ModelEntityMapper.selectByModelId(Integer.valueOf(modelId));
                        if(entity != null)
                            model.put("fuelType",entity.getFuelType());
                        else
                            model.put("fuelType",-1);
                    }catch (Exception e){
                        model.put("fuelType",-1);
                    }
                    modelArray.add(model);
                }
                return ResponseFactory.success(modelArray);
            } else {
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, data.getString("error_msg"));
            }
        }
        return new Response().fail(SystemErrorCodeEnum.CRS_NO_DATA_FOUND);
    }

    /**
     * 根据获取车辆品牌
     *
     * @return
     */
    @ApiMapping(value="cheyiping.getCarBrandList",desc="车易评.获取车辆品牌")
    public Response getCarBrandList(PageRequest requestEntity) {
        Response response = ValidUtil.valid(requestEntity);
        if (response != null)
            return response;
        int total = car300BrandEntityMapper.selectCount(null);
        List<Car300BrandEntity> list = car300BrandEntityMapper.selectByPage(Integer.valueOf(requestEntity.getPageSize()),
                requestEntity.getOffset(), null);
        return ResponseFactory.success(pageResult(total, processArrayGetCarBrand(list)));
    }
    /**
     * 根据获取车辆品牌（不分页）
     *
     * @return
     */
    @ApiMapping(value="cheyiping.getCarBrandAll",desc="车易评.根据获取车辆品牌（不分页）")
    public Response getCarBrandAll(Car300BrandEntity car300BrandEntity) {
        int total = car300BrandEntityMapper.selectCount(null);
        List<Car300BrandEntity> list = car300BrandEntityMapper.queryAll(car300BrandEntity);
        return ResponseFactory.success(pageResult(total, processArrayGetCarBrand(list)));
    }

    private JSONArray processArrayGetCarBrand(List<Car300BrandEntity> list){
        JSONArray array = new JSONArray();
        for (Car300BrandEntity brand : list) {
            JSONObject item = new JSONObject();
            item.put("brandId", brand.getBrandId());
            item.put("brandName", brand.getBrandName());
            item.put("intial", brand.getInitial());
            array.add(item);
        }
        return array;
    }

    private JSONObject pageResult(int total, JSONArray array) {
        JSONObject data = new JSONObject();
        data.put("total", total);
        data.put("list", array);
        return data;
    }

    /**
     * 获取车系列表
     *
     * @param req
     * @return
     */
    @ApiMapping(value="cheyiping.getCarSeriesList",desc="车易评.获取车系列表")
    public Response getCarSeriesList(CheyipingRequest.GetCarSeriesListRequest req) {
        Response response = ValidUtil.valid(req);
        if (response != null)
            return response;

        Integer brandId = Integer.valueOf(req.getBrandId());
        List<Car300SeriesEntity> list = car300SeriesEntityMapper.selectByPage(brandId, req.getPageSizeAsInteger(), req.getOffset(), null);
        int total = car300SeriesEntityMapper.selectCount(brandId, null);
        return ResponseFactory.success(pageResult(total, processArrayGetCarSeries(list)));
    }

    /**
     * 获取车系列表（不分页）
     *
     * @param req
     * @return
     */
    @ApiMapping(value="cheyiping.getCarSeriesAll",desc="车易评.获取车系列表（不分页）")
    public Response getCarSeriesAll(CheyipingRequest.GetCarSeriesListRequest req) {
        Integer brandId = Integer.valueOf(req.getBrandId());
        int total = car300SeriesEntityMapper.selectCount(brandId, null);
        List<Car300SeriesEntity> list = car300SeriesEntityMapper.selectAll(brandId,null);
        return ResponseFactory.success(pageResult(total, processArrayGetCarSeries(list)));
    }

    private JSONArray processArrayGetCarSeries(List<Car300SeriesEntity> list){
        JSONArray array = new JSONArray();
        for (Car300SeriesEntity series : list) {
            JSONObject item = new JSONObject();
            item.put("seriesId", series.getSeriesId());
            item.put("seriesName", series.getSeriesName());
            item.put("seriesGroupName", series.getSeriesGroupName());
            array.add(item);
        }
        return array;
    }

    /**
     * 获取车型列表
     * @param req
     * @return
     */
    @ApiMapping(value="cheyiping.getCarModelList",desc="车易评.获取车型列表")
    public Response getCarModelList(CheyipingRequest.GetCarModelListRequest req) {
        Response response = ValidUtil.valid(req);
        if (response != null)
            return response;

        int seriesId = Integer.valueOf(req.getSeriesId());
        List<Car300ModelEntity> list = car300ModelEntityMapper.selectByPage(seriesId, req.getPageSizeAsInteger(), req.getOffset());
        int total = car300ModelEntityMapper.selectCount(seriesId);
        return ResponseFactory.success(pageResult(total, processArrayGetCarModel(list)));
    }

    /**
     * 获取车型列表-不分页
     * @param req
     * @return
     */
    @ApiMapping(value="cheyiping.getCarModelAll",desc="车易评.获取车型列表-不分页")
    public Response getCarModelAll(CheyipingRequest.GetCarModelListRequest req) {
        int seriesId = Integer.valueOf(req.getSeriesId());
        List<Car300ModelEntity> list = car300ModelEntityMapper.selectAll(seriesId);
        int total = car300ModelEntityMapper.selectCount(seriesId);
        return ResponseFactory.success(pageResult(total, processArrayGetCarModel(list)));
    }

    private JSONArray processArrayGetCarModel(List<Car300ModelEntity> list){
        JSONArray array = new JSONArray();
        for (Car300ModelEntity model : list) {
            JSONObject item = new JSONObject();
            item.put("modelId", model.getModelId());
            item.put("modelName", model.getModelName());
            item.put("modelPrice", model.getModelPrice());
            item.put("modelYear", model.getModelYear());
            item.put("minRegYear", model.getMinRegYear());
            item.put("maxRegYear", model.getMaxRegYear());
            item.put("liter", model.getLiter());
            item.put("gearType", model.getGearType());
            item.put("dischargeStandard", model.getDischargeStandard());
            item.put("seatNumber", model.getSeatNumber());
            item.put("updateTime", model.getUpdateTime());
            item.put("fuelType", model.getFuelType());
            array.add(item);
        }
        return array;
    }

    /**
     * 获取车辆价格
     *
     * @param req
     * @return
     */
    @ApiMapping(value="cheyiping.getCarPrice",desc="车易评.获取车辆价格")
    public Response getCarPrice(Car300PriceRequestEntity req) {
        //step1: 校验
        Response response = ValidUtil.valid(req);
        if (response != null)
            return response;

        if (!colors.contains(req.getColor()))
            req.setColor("其他");
        String zone = req.getZone();
        long startTime = System.currentTimeMillis();
        if(car300Properties.getIsUseCityCode().equals("Y")){
            Map<String, Object> cityMap = cityEntityMapper.selectByGbCityCode(zone);
            logger.info("车易评查询城市编码cost:" + (System.currentTimeMillis() - startTime));
            if (cityMap == null) {
//                return ResponseFactory.fail(SystemErrorCodeEnum.CRS_PARAM_CHECK_FAILED,"zone无法匹配");
                zone = zone.substring(0,zone.length()-2)+"00";
            }else{
                //step2: 车300调用
                //城市编码由国标码转成车300编码
                zone = String.valueOf(cityMap.get("car300CityCode"));
            }

        }else{
            zone = zone.substring(0,zone.length()-2)+"00";
        }


        StringBuilder errorMsg = new StringBuilder();
        final String crNo = TracerContextUtil.getTraceId();

        boolean skipCar300 = false;
        //TODO 仅用于测试
//        skipCar300 = true;
        String car300Status = "";
        final int timeout = 6; //超时设置为6秒
        if(!skipCar300){
            if (zone != null) {
                req.setModelType("che300");
                req.setZone(zone);
                Response car300Res = null;
                Future<Response> car300ResFuture =
                threadPool.submit(() ->{
                    try {
                        TracerContextUtil.attachTraceId(crNo);
                        long startTime1 = System.currentTimeMillis();
                        Response car300ResInTask = car300Client.getCarPrice(req);
                        long cost = System.currentTimeMillis() - startTime1;
                        logger.info("车300,cost:{},result:{}",cost,car300ResInTask);
                        TracerContextUtil.removeTraceId();
                        return car300ResInTask;
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                        return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
                    }
                });

                try {
                    car300Res = car300ResFuture.get(timeout,TimeUnit.SECONDS);
                } catch (InterruptedException | ExecutionException e) {
                    logger.error(e.getMessage(),e);
                    car300Status += e.getMessage();
                }  catch (TimeoutException e) {
                    logger.error(e.getMessage(),e);
                    car300Status += "超时"+timeout+"秒";
                }

                if (car300Res != null) {
                    if (car300Res.checkIfSuccess() && !StringUtils.isEmpty(car300Res.getData())) {
                        try {
                            JSONObject obj = (JSONObject) JSON.parseObject(String.valueOf(car300Res.getData()));
                            if (obj.getInteger("status") == 1) {
                                double c2bPrice = obj.getJSONObject("eval_prices").getDouble("c2b_price");
                                double b2cPrice = obj.getJSONObject("eval_prices").getDouble("b2b_price");
                                //处理new_car_price = [] 的情况，将[]改成{}
                                try{
                                    Object newCarPriceObj = obj.get("new_car_price");
                                    if(newCarPriceObj instanceof JSONArray){
                                        JSONArray jArr = (JSONArray)newCarPriceObj;
                                        JSONObject jObj = null;
                                        if(jArr.size() > 0){
                                            jObj = jArr.getJSONObject(0);
                                        }else{
                                            jObj = new JSONObject();
                                        }
                                        obj.put("new_car_price",jObj);
                                    }
                                }catch (Exception e){
                                    logger.error(e.getMessage(),e);
                                }

                                JSONObject data = new JSONObject();
                                data.put("che300", obj);
                                data.put("c2b_price", c2bPrice);
                                data.put("b2c_price", b2cPrice); //为乐高系统增加的
                                data.put("source","che300");
                                return ResponseFactory.success(data);
                            } else {
                                String msg = obj.getString("error_msg");
                                car300Status = msg;
                                errorMsg.append(msg);
                                logger.error("车300估价查询结果异常,request:{},message:{}", req, msg);
                            }
                        } catch (Exception e) {
                            car300Status = e.getMessage();
                            logger.error("车300估价查询结果异常,result:" + car300Res.getData(), e);
                        }
                    } else {
                        car300Status = car300Res.getCode() + ":"+car300Res.getMsg();
                        logger.info("车300结果：" + car300Res.toString());
                    }
                }else{
                    //结果异常，已经捕获
                }
            }else{
                car300Status = "没找到对应的城市编码，国标码："+ req.getZone();
            }
        }else{
            car300Status = "测试跳过车300，生产时需关闭";
        }

       /* //城市编码由国标码转成车精真估城市编码
        zone = String.valueOf(cityMap.get("jzgCityCode"));
        //获取车300对应精真估车型ID
        int car300ModelId = 0;
        int jzgModelId = 0;
        try {
            car300ModelId = Integer.valueOf(req.getModelId());
            ModelMapEntityExample example = new ModelMapEntityExample();
            example.createCriteria().andCar300ModelIdEqualTo(car300ModelId);
            List<ModelMapEntity> modelMapEntityList = modelMapEntityMapper.selectByExample(example);
            if (modelMapEntityList != null && modelMapEntityList.size() > 0) {
                jzgModelId = modelMapEntityList.get(0).getJzgModelId();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        if (jzgModelId == 0) {
            modelUnmapedEntityMapper.insertModelId(car300ModelId);
            logger.info("【车易评估车】找不到车300 对应精真估的车型Id" + req.getModelId());
        }

        String jzgStatus = "";
        if (zone != null && jzgModelId > 0) {
            JzgRequestEntity.CarPriceRequest carPriceRequest = new JzgRequestEntity.CarPriceRequest();
            carPriceRequest.setCityId(zone);
            carPriceRequest.setBuyCarDate(req.getRegDate());
            // 精真估里程单位为公里，需要转换
            String mile;
            try {
                mile = String.valueOf((int) (10000 * Double.valueOf(req.getMile())));
            } catch (Exception e) {
                logger.error(e);
                mile = req.getMile();
            }
            carPriceRequest.setMileage(mile);
            carPriceRequest.setTrimId(String.valueOf(jzgModelId));

            Response jzgRes = null;
            Future<Response> jzgResFuture =
            threadPool.submit(()->{
                try {
                    TracerContextUtil.attachTraceId(crNo);

                    long startTime1 = System.currentTimeMillis();
                    Response jzgResInTask = jingZhenGuClient.estimate(carPriceRequest);
                    long cost = System.currentTimeMillis() - startTime1;
                    logger.info("精真估，cost:{},result:{}",cost,jzgResInTask);

                    TracerContextUtil.removeTraceId();
                    return jzgResInTask;
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                    return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
                }
            });

            try {
                jzgRes = jzgResFuture.get(timeout,TimeUnit.SECONDS);
            } catch (InterruptedException | ExecutionException e) {
                jzgStatus += e.getMessage();
            }catch (TimeoutException e) {
                jzgStatus += "超时"+timeout+"秒";
            }

            if (jzgRes != null){
                if(jzgRes.checkIfSuccess() && !StringUtils.isEmpty(jzgRes.getData())) {
                    try {
                        JSONObject obj = JSON.parseObject(String.valueOf(jzgRes.getData()));
                        if (obj.getInteger("errorCode") == 0) {
                            double c2bPrice = obj.getJSONObject("body").getJSONObject("c2BPrices").getDouble("a");
                            double k = ratio[levelIndex(req.getInterior())][0] * ratio[levelIndex(req.getSurface())][1] * ratio[levelIndex(req.getWorkState())][2];
                            c2bPrice = c2bPrice * k;
                            c2bPrice = Double.parseDouble(Common.format(c2bPrice,"#.00"));

                            JSONObject data = new JSONObject();
                            data.put("che300", new JSONObject());
                            data.put("c2b_price", c2bPrice);

                            //监控状态
                            JSONObject statusObj = new JSONObject();
                            statusObj.put("car300", car300Status);
                            data.put("srcStatus",statusObj);
                            data.put("source","jingzhengu");
                            return ResponseFactory.success(data);
                        } else {
                            String msg = obj.getString("Msg");
                            jzgStatus = msg;
                            errorMsg.append(msg);
                            logger.error("精真估估价查询结果异常,{}", msg);
                        }
                    } catch (Exception e) {
                        jzgStatus = e.getMessage();
                        logger.error("精真估估价查询结果异常,result: " + jzgRes.getData(), e);
                    }
                }else{
                    jzgStatus = jzgRes.getCode() + ":"+jzgRes.getMsg();
                    logger.info("精真估结果：" + jzgRes.toString());
                }
            } else {
                //精真估结果异常
            }
        }else{
            jzgStatus = "精真估对应的城市编码不存在，国标码：" + req.getZone();
        }*/
        return ResponseFactory.fail(SystemErrorCodeEnum.CRS_NO_DATA_FOUND);
    }

    private JSONObject getStatusObjOfCarPrice(String car300Status,String jzgStatus){
        if(car300Status == null)
            car300Status = "";
        if(jzgStatus == null)
            jzgStatus = "";
        JSONObject statusObj = new JSONObject();
        statusObj.put("car300", car300Status);
        statusObj.put("jingzhengu",jzgStatus);
        return statusObj;
    }

    private int levelIndex(String str) {
        switch (str) {
            case "优":
                return 0;
            case "良":
                return 1;
            case "中":
                return 2;
            case "差":
                return 3;
        }
        return 0;
    }

    @Autowired
    private ChaboshiService chaboshiService;

    @Autowired
    private CarIdentifyService carIdentifyService;

    @Autowired
    private TcreditService tcreditService;

    private int maintenanceRecordRequestInterval = 5;




    @ApiMapping(value="cheyiping.getMaintenanceRecord",desc="车易评.获取车辆维修记录")
    public Response getMaintenanceRecord(MaintenanceRecordRequest request){

        Response response = ValidUtil.valid(request);
        if(response != null){
            return response;
        }
        String crNo = TracerContextUtil.getTraceId();

        //处理茶博士接口
        Future<Response> cbsFuture = null;
        cbsFuture = threadPool.submit(()-> {
            try{
                TracerContextUtil.attachTraceId(crNo);
                Response cbxResponse = chaboshiService.getReport(request);
                TracerContextUtil.removeTraceId();
                return cbxResponse;
            }catch (Exception e){
                logger.error(e.getMessage(),e);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
            }
        });

        JSONObject status = new JSONObject();
        try {
            if(cbsFuture != null){
                response = cbsFuture.get(maintenanceRecordRequestInterval, TimeUnit.MINUTES);
                if(response.checkIfSuccess()){
                    JSONObject data = (JSONObject)response.getData();
                    JSONObject result = new JSONObject();
                    JSONObject basicObj = new JSONObject();
                    Common.jsonFieldCopy(data,basicObj,"vin");
                    Common.jsonFieldCopy(data,basicObj,"modelName","model");
                    Common.jsonFieldCopy(data,basicObj,"makeDate","year");
                    basicObj.put("brand","");
                    Common.jsonFieldCopy(data,basicObj,"displacement");
                    basicObj.put("gearbox","");
                    Common.jsonFieldCopy(data,basicObj,"effluentStandard");
                    result.put("basic",basicObj);

                    JSONObject resumeObj = new JSONObject();
                    Common.jsonFieldCopy(data,resumeObj,"carConstructRecordsFlag","componentFlag");
                    resumeObj.put("gasbagFlag","");
                    Common.jsonFieldCopy(data,resumeObj,"mileageIsNormalFlag","odometerFlag");
                    resumeObj.put("maintenanceTimes","");
                    resumeObj.put("maxMileage","");
                    resumeObj.put("engineFlag","");
                    resumeObj.put("gearboxFlag","");
                    Common.jsonFieldCopy(data,resumeObj,"carOutsideRecordsFlag");
                    Common.jsonFieldCopy(data,resumeObj,"carComponentRecordsFlag");
                    resumeObj.put("lastdate","");
                    resumeObj.put("exteriorDesc","");
                    Common.jsonFieldCopy(data,resumeObj,"carWaterFlag","waterFlag");
                    Common.jsonFieldCopy(data,resumeObj,"carFireFlag","fireFlag");
                    resumeObj.put("majorAccident","");
                    resumeObj.put("configuration","");
                    result.put("resume",resumeObj);

                    JSONObject reportObj = new JSONObject();
                    reportObj.put("content","");
                    JSONArray records = data.getJSONArray("outsideAnalyzeRepairRecords");
                    JSONArray recordArr = new JSONArray();
                    if(records != null && records.size() > 0){
                        for(int i = 0;i< records.size();i++){
                            JSONObject record = records.getJSONObject(i);
                            JSONObject recordObj = new JSONObject();
                            recordObj.put("content","");
                            Common.jsonFieldCopy(record,recordObj,"materal","material");
                            Common.jsonFieldCopy(record,recordObj,"mileage","mileage");
                            Common.jsonFieldCopy(record,recordObj,"date","repairDate");
                            Common.jsonFieldCopy(record,recordObj,"type","type");
                            recordObj.put("recordStatus","");
                            recordObj.put("source","");
                            recordArr.add(recordObj);
                        }
                    }
                    result.put("report",recordArr);
                    result.put("source","查博士");
                    result.put("status",status);
                    return ResponseFactory.success(result);
                }else {
                    status.put("chaboshi",response.getMsg());
                }
            }
        } catch (InterruptedException e) {
            status.put("查博士",e.getMessage());
            logger.error("",e);
        } catch (ExecutionException e) {
            logger.error("",e);
            status.put("查博士",e.getMessage());
        } catch (TimeoutException e) {
            logger.error("",e);
            status.put("查博士",e.getMessage());
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            status.put("查博士",e.getMessage());
        }

        //车鉴定
        Future<Response> cjdFuture = null;
        cjdFuture = threadPool.submit(()-> {
            try{
                TracerContextUtil.attachTraceId(crNo);
                Response response1 = carIdentifyService.getReport(request);
                TracerContextUtil.removeTraceId();
                return response1;
            }catch (Exception e){
                logger.error(e.getMessage(),e);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
            }
        });

        try {
            if(cjdFuture != null){
                response = cjdFuture.get(maintenanceRecordRequestInterval, TimeUnit.MINUTES);
                if(response.checkIfSuccess()){
                    JSONObject data = (JSONObject)response.getData();
                    JSONObject result = new JSONObject();

                    JSONObject basicObj = new JSONObject();
                    JSONObject basic = data.getJSONObject("basic");
                    Common.jsonFieldCopy(basic,basicObj,"vin");
                    Common.jsonFieldCopy(basic,basicObj,"model");
                    Common.jsonFieldCopy(basic,basicObj,"year");
                    Common.jsonFieldCopy(basic,basicObj,"brand");
                    Common.jsonFieldCopy(basic,basicObj,"displacement");
                    Common.jsonFieldCopy(basic,basicObj,"gearbox");
                    Common.jsonFieldCopy(basic,basicObj,"pfsp","effluentStandard");
                    //basic->pfsp
                    result.put("basic",basicObj);

                    JSONObject resume = data.getJSONObject("resume");
                    JSONObject resumeObj = new JSONObject();

                    Common.jsonFieldCopy(resume,resumeObj,"sd","componentFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"ab","gasbagFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"mi","odometerFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"ronum","maintenanceTimes");
                    Common.jsonFieldCopy(resume,resumeObj,"mile","maxMileage");
                    Common.jsonFieldCopy(resume,resumeObj,"en","engineFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"tr","gearboxFlag");
                    resumeObj.put("carOutsideRecordsFlag","");
                    resumeObj.put("carComponentRecordsFlag","");
                    Common.jsonFieldCopy(resume,resumeObj,"lastdate","lastdate");
                    Common.jsonFieldCopy(resume,resumeObj,"wgjdesc","exteriorDesc");
                    Common.jsonFieldCopy(resume,resumeObj,"sp","waterFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"hs","fireFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"bf","majorAccident");
                    Common.jsonFieldCopy(resume,resumeObj,"remark","configuration");
                    result.put("resume",resumeObj);

                    JSONArray reportJson = data.getJSONArray("reportJson");
                    JSONArray reportArr = new JSONArray();
                    if(reportJson != null && reportJson.size() > 0){
                        for(int i = 0 ; i < reportJson.size();i++){
                            JSONObject record = reportJson.getJSONObject(i);
                            JSONObject recordObj = new JSONObject();
                            Common.jsonFieldCopy(record,recordObj,"content","content");
                            Common.jsonFieldCopy(record,recordObj,"material","material");
                            Common.jsonFieldCopy(record,recordObj,"mileage","mileage");
                            Common.jsonFieldCopy(record,recordObj,"repairDate","repairDate");
                            Common.jsonFieldCopy(record,recordObj,"type","type");
                            recordObj.put("recordStatus","");
                            recordObj.put("source","");
                            reportArr.add(recordObj);
                        }
                    }
                    result.put("report",reportArr);
                    result.put("source","车鉴定");
                    result.put("srcStatus",status);
                    return ResponseFactory.success(result);
                }else{
                    status.put("车鉴定",response.getMsg());
                }
            }
        } catch (InterruptedException e) {
            status.put("车鉴定",e.getMessage());
            logger.error("",e);
        } catch (ExecutionException e) {
            logger.error("",e);
            status.put("车鉴定",e.getMessage());
        } catch (TimeoutException e) {
            logger.error("",e);
            status.put("车鉴定",e.getMessage());
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            status.put("车鉴定",e.getMessage());
        }

        Future<Response> tcFuture = null;
        tcFuture = threadPool.submit(()-> {
            try{
                TracerContextUtil.attachTraceId(crNo);
                Response response1 = tcreditService.getReport(request);
                TracerContextUtil.removeTraceId();
                return response1;
            }catch (Exception e){
                logger.error(e.getMessage(),e);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
            }
        });

        try {
            if(tcFuture != null){
                response = tcFuture.get(maintenanceRecordRequestInterval, TimeUnit.MINUTES);
                if(response.checkIfSuccess()){
                    JSONObject result = new JSONObject();
                    JSONObject data1 = (JSONObject) response.getData();
                    JSONObject data = data1.getJSONObject("data");

                    JSONObject basic = data.getJSONObject("basic");
                    JSONObject basicObj = new JSONObject();

                    Common.jsonFieldCopy(basic,basicObj,"vin");
                    Common.jsonFieldCopy(basic,basicObj,"model");
                    Common.jsonFieldCopy(basic,basicObj,"year");
                    Common.jsonFieldCopy(basic,basicObj,"brand");
                    Common.jsonFieldCopy(basic,basicObj,"displacement");
                    Common.jsonFieldCopy(basic,basicObj,"gearbox");
                    Common.jsonFieldCopy(basic,basicObj,"effluentStandard");
                    result.put("basic",basicObj);

                    JSONObject resume = data.getJSONObject("resume");
                    JSONObject resumeObj = new JSONObject();

                    Common.jsonFieldCopy(resume,resumeObj,"componentFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"gasbagFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"odometerFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"maintenanceTimes");
                    Common.jsonFieldCopy(resume,resumeObj,"maxMileage");
                    Common.jsonFieldCopy(resume,resumeObj,"engineFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"gearboxFlag");
                    resumeObj.put("carOutsideRecordsFlag","");
                    resumeObj.put("carComponentRecordsFlag","");
                    Common.jsonFieldCopy(resume,resumeObj,"lastdate");
                    Common.jsonFieldCopy(resume,resumeObj,"exteriorDesc");
                    Common.jsonFieldCopy(resume,resumeObj,"waterFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"fireFlag");
                    Common.jsonFieldCopy(resume,resumeObj,"majorAccident");
                    Common.jsonFieldCopy(resume,resumeObj,"configuration");
                    result.put("resume",resumeObj);

                    JSONArray report = data.getJSONArray("report");
                    JSONArray reportArr = new JSONArray();
                    if(report != null && report.size() > 0){
                        for(int i = 0;i<report.size();i++){
                            JSONObject record = report.getJSONObject(i);
                            JSONObject recordObj = new JSONObject();
                            Common.jsonFieldCopy(record,recordObj,"content");
                            Common.jsonFieldCopy(record,recordObj,"material");
                            Common.jsonFieldCopy(record,recordObj,"mileage");
                            Common.jsonFieldCopy(record,recordObj,"repairDate");
                            Common.jsonFieldCopy(record,recordObj,"type");
                            Common.jsonFieldCopy(record,recordObj,"recordStatus");
                            Common.jsonFieldCopy(record,recordObj,"source");
                            reportArr.add(recordObj);
                        }
                    }
                    result.put("report",reportArr);
                    result.put("source","天创维修记录");
                    result.put("srcStatus",status);
                    return ResponseFactory.success(result);
                }else{
                    status.put("tianchuang.weixiujilu",response.getMsg());
                }
            }
        } catch (InterruptedException e) {
            status.put("天创维修记录",e.getMessage());
            logger.error("",e);
        } catch (ExecutionException e) {
            status.put("天创维修记录",e.getMessage());
            logger.error("",e);
        } catch (TimeoutException e) {
            status.put("天创维修记录",e.getMessage());
            logger.error("",e);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            status.put("天创维修记录",e.getMessage());
        }

        //天创出险详单
        Future<Response> insuranceFuture = threadPool.submit(()-> {
            try{
                TracerContextUtil.attachTraceId(crNo);
                Response response1 = tcreditService.vehicleInsuranceRec(request.getPlateNo(),request.getVin());
                TracerContextUtil.removeTraceId();
                return response1;
            }catch (Exception e){
                logger.error(e.getMessage(),e);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_SYSTEM_ERROR,e.getMessage());
            }
        });

        if(insuranceFuture != null){
            try {
                response = insuranceFuture.get(maintenanceRecordRequestInterval, TimeUnit.MINUTES);
                if(response.checkIfSuccess()){
                    JSONObject resObj = (JSONObject) response.getData();
                    JSONObject data = resObj.getJSONObject("data");
                    int queryStatus = data.getInteger("queryStatus");
                    if(0 == queryStatus){
                        JSONObject result = new JSONObject();
                        result.put("overview",data.getJSONObject("overview"));
                        result.put("records",data.getJSONArray("records"));
                        result.put("source","天创出险详情");
                        result.put("srcStatus",status);
                        return ResponseFactory.success(result);
                    }else{
                        status.put("天创出险详情",data.getString("queryMsg"));
                    }
                }else{
                    status.put("天创出险详情",response.getMsg());
                }
            } catch (InterruptedException e) {
                status.put("天创出险详情",e.getMessage());
                logger.error("",e);
            } catch (ExecutionException e) {
                status.put("天创出险详情",e.getMessage());
                logger.error("",e);
            } catch (TimeoutException e) {
                status.put("天创出险详情",e.getMessage());
                logger.error("",e);
            }catch (Exception e){
                status.put("天创出险详情",e.getMessage());
                logger.error("",e);
            }
        }
        return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR,"无数据,详情：" + status.toJSONString());
    }
}
